'use client'

import Image from 'next/image'
import pdfIcon from '@/public/pdf.png'
import html2canvas from 'html2canvas'
import jsPDF from 'jspdf'

interface GeneratePDFButtonProps {
  children: React.ReactNode
}

const GeneratePDFButton: React.FC<GeneratePDFButtonProps> = (props) => {
  const { children } = props

  const capturePageAndDownloadPDF = () => {
    html2canvas(document.body).then((canvas) => {
      // 获取网页的实际宽度和高度
      const webpageWidth = canvas.width
      const webpageHeight = canvas.height

      // 转换网页尺寸从像素到毫米
      const widthInMM = webpageWidth / 3.78
      const heightInMM = webpageHeight / 3.78

      // 初始化 jsPDF，设置PDF页面大小为网页的大小
      const pdf = new jsPDF({
        orientation: 'p',
        unit: 'mm',
        format: [widthInMM, heightInMM],
      })

      // 将canvas转换为图片
      const imgData = canvas.toDataURL('image/jpeg', 1.0)

      // 因为PDF页面大小已经调整为网页的大小，这里可以直接使用网页尺寸
      pdf.addImage(imgData, 'JPEG', 0, 0, widthInMM, heightInMM)
      pdf.save('download.pdf')
    })
  }

  return (
    <button
      className='flex justify-center items-center px-[0.59375rem] py-[0.5rem] bg-[#91B01C] rounded-[5px] text-white text-[0.875rem] leading-[0.875rem] font-medium lg:px-[0.8125rem] lg:py-[0.4375rem] lg:rounded-[0.4375rem] 2xl:rounded-[0.65625rem] 2xl:px-[1.21875rem] 2xl:py-[0.65625rem] 2xl:text-[1.3125rem] 2xl:leading-[1.3125rem]'
      onClick={capturePageAndDownloadPDF}
    >
      <div className='relative w-[0.875rem] h-[0.875rem] lg:w-[1.1875rem] lg:h-[1.1875rem] 2xl:w-[1.78125rem] 2xl:h-[1.78125rem]'>
        <Image
          src={pdfIcon}
          alt='pdf icon'
          fill
          sizes='(max-width: 1024px) 5vw'
        />
      </div>
      <div className='2xl:w-1' />
      <div className='w-1' />
      {children}
    </button>
  )
}

export default GeneratePDFButton
